import * as api from '@/services/idcApiEvent';
import { PageContainer } from '@ant-design/pro-components';
import { ProFormInstance } from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Collapse, Popconfirm, Space, Tag } from 'antd';
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';
import ManualForm from './ManualForm';
import ReportForm from './ReportForm';
import * as utils from '@/utils/utils';
import * as c from '@/services/consts';
import Countdown from 'antd/es/statistic/Countdown';
import { ClockCircleOutlined, RedoOutlined, UserOutlined } from '@ant-design/icons';
const { Panel } = Collapse;
import IdcApiEventStatusTag from '@/components/IdcApiEventStatusTag';

const OrderList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();

  const { hasRight } = useModel('useAuthModel');

  const [formReportVisible, setFormReportVisible] =useState<boolean>(false);
  const [formManualVisible, setFormManualVisible] =useState<boolean>(false);
  const [currentId, setCurrentId] = useState<string | undefined>(undefined);
  const [countdownTicks, setCountdownTicks] = useState<number>(Date.now() + 60000,);
  
  // const { getSupplier } = useModel('useGlobalModel', (model) => ({
  //   getSupplier: model.getSupplier,
  // }));
    
  const reload = () => {
    actionRef.current?.reload();
    setCountdownTicks(Date.now() + 60000);
  };

  
  const handleRemove = async (id: string) => {
    const result = await api.remove({ key: id });
    if (result.success) {
      actionRef?.current?.clearSelected();
      reload();
    }
  };

  const handleRemoves = async (ids:any[]) => {
    const result = await api.removes({keys:ids});
    if (result && result.success) {
      actionRef?.current?.clearSelected();
      reload();
    }
  };

  let columns: ProColumns<API.IdcApiEvent>[] = [
    {
      title: '版本',
      dataIndex: 'id',
      width: 200,
      sorter: true,
      render: (_, record) => {
        let actionTitle = c.getObjectText(c.IdcApiEventActionOptions, record.action);
        return (
          <><div style={{marginBottom:5}}>
          <IdcApiEventStatusTag status={record.status} />
          </div>
          <Tag color={utils.getTextRanColor(actionTitle)}>{actionTitle}</Tag>
          <Tag color={utils.getTextRanColor(record.code)}>{record.code}</Tag>
          <div>{record.id}</div>
          {record.checkScheduleId ? <div><RedoOutlined />{record.checkScheduleId}</div> : ''}
          {record.createUser ? <div style={{color:'#aaa'}}><UserOutlined /> {record.createUser}</div> : ''}
          {record.createTime ? <div style={{color:'#aaa'}}><ClockCircleOutlined /> {utils.formatDate(record.createTime)}</div> : ''}
          <div style={{color:'#aaa'}}>{record.apiUrl}</div>
          </>
        );
      },
    },
    
    {
      title: '内容',
      dataIndex: 'instanceIds',
      search: false,
      sorter: true,
      render: (_, record) => {
        // return <>
        //   {record.details?.map((val)=>{
        //   return <Tag color='blue'>{val.instanceId}</Tag>
        // })}
        
        return <>
        {/* {record.schedule ? <><div><Tag color="blue">定时检测间隔：{record.schedule?.interval}分钟</Tag></div></> : ''}
        {record.serverIds ? <div style={{marginBottom:10}}><h4>检测服务器</h4>
          {record.serverIds.map((sid)=>{
          let ser = record.progresss?.filter((el)=>el.serverId == sid);
          return ser && ser.length > 0 
            ? <Tag color={ser[0].percent == 100 ? 'green' : ser[0].percent >= 0 ? 'blue' : ''}>{ser[0].serverId} {ser[0].percent}%</Tag>
            : <><Tag>{sid}</Tag></>        
        })}</div> : ''} */}
        
        <Collapse style={{marginBottom:10}} defaultActiveKey={['33']} ghost size='small'><Panel key="33" header={<>
          {record.policy?.disableCheckIpBlacklist == true ? <Tag color='orange'>不检查IP黑名单</Tag> : ''}
          {record.name ? <span style={{color:'#D48806'}}><b>操作：{record.name}</b></span> : <b>操作项</b>}
          {record.remark || record.parentId ? <span style={{color:'#999'}}> {record.remark}{record.parentId ? ` [P:${record.parentId}]` : ''}</span> : ''}
          {record.apiMessage || record.apiMessage != '完成' ? <span style={{color:'#999'}}> {record.apiMessage}</span> : ''}
        </>}>
          
        {record.failures && record.failures.length > 0 ? <div style={{marginBottom:10, color:'red'}}><h4>更换失败实例ID</h4>
          {record.failures.map((sid)=>{
          return <Tag color="error">{sid}</Tag>
        })}</div> : ''}

        {/* {record.supplierIds && record.supplierIds.length > 0 ? <div style={{marginBottom:10}}><h4>服务器提供商</h4>
          {record.supplierIds.map((sid)=>{
          return <Tag color="blue">{getSupplier(sid)?.name}</Tag>
        })}</div> : ''} */}

        {record.groupNames && record.groupNames.length > 0 ? <div style={{marginBottom:10}}><h4>分组</h4>
          {record.groupNames.map((sid)=>{
          return <Tag color="blue">{sid}</Tag>
        })}</div> : ''}

        {record.instanceIds && record.instanceIds.length > 0 ? <div style={{marginBottom:10}}><h4>实例ID</h4>
          {record.instanceIds.map((sid)=>{
          //return record.failures && record.failures.length >0 && record.failures.includes(Number(sid)) ?  <Tag color="error">{sid}</Tag> : <Tag color="blue">{sid}</Tag>
          return <Tag color="blue">{sid}</Tag>
        })}</div> : ''}

        {record.serverIps && record.serverIps.length > 0 ? <div style={{marginBottom:10}}><h4>实例IP</h4>
          {record.serverIps.map((sid)=>{
          return <Tag color="blue">{sid}</Tag>
        })}</div> : ''}
        
        </Panel></Collapse>
        </>
      },
    },
    
    {
      title: '状态',
      dataIndex: 'status',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        mode: 'single',
        allowClear: true,
        showSearch: true,
        options: c.IdcApiEventStatusOptions,
      },
    },
    {
      title: '动作',
      dataIndex: 'action',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        mode: 'single',
        allowClear: true,
        showSearch: true,
        options: c.IdcApiEventActionOptions,
      },
    },
    {
      title: '操作代码',
      dataIndex: 'code',
      hideInTable: true,
      valueType: 'text',
    },
    {
      title: '自定义名称',
      dataIndex: 'name',
      hideInTable: true,
      valueType: 'text',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      hideInTable: true,
      valueType: 'text',
    },

  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 120,
      render: (_, record) => {
        let cmps = [];        

        if (hasRight('idcapievent_list')) {
          cmps.push(
            <a
              key="idcapievent_report"
              onClick={() => {
                setCurrentId(record.id);
                setFormReportVisible(true);
              }}
            >
              操作结果
            </a>,
          );
        }

        if (hasRight('idcapievent_delete')) {
          cmps.push(
            <Popconfirm
              key="delete"
              title="确定要删除吗?"
              onConfirm={async () => {
                await handleRemove(record.id);
              }}
            >
              <a>删除</a>
            </Popconfirm>,
          );
        }

        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        formRef={formRef}
        search={{
          defaultCollapsed: false,
          span: 4,
        }}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        toolBarRender={() => {
          var toolbarDoms: any[] = [];

          if (hasRight('idcapievent_create')) {
            toolbarDoms.push([
              <Button
                type="primary"
                key="create_check_manual"
                onClick={() => {
                  setFormManualVisible(true);
                }}
              >
               自定义操作
              </Button>
            ]);
          }

          
          // if (hasRight('checktask_update')) {
          //   toolbarDoms.push([
          //     <Button
          //       type="primary"
          //       danger
          //       key="checktask_publish"
          //       onClick={async() => {
          //         await handlePublish(undefined);
          //       }}
          //     >
          //      下发配置
          //     </Button>
          //   ]);
          // }

          toolbarDoms.push([
            <span>
            <Countdown
              title=""
              key="cdRefresh"
              value={countdownTicks}
              format="s"
              prefix=""
              suffix="秒后刷新"
              valueStyle={{
                fontSize: 14,
                color: 'gray',
              }}
              onFinish={reload}
            />
          </span>
          ]);

          return toolbarDoms;
        }}
        rowSelection={{
          defaultSelectedRowKeys: [],
        }}
        tableAlertRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 条记录
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消
              </a>
            </span>
            

            <span>
              {hasRight('idcapievent_delete') ?
                  <Popconfirm
                    key="check_delete"
                    title="确定要删除吗?"
                    onConfirm={async () => {
                      await handleRemoves(selectedRowKeys);
                    }}
                  >
                    <a>删除</a>
                  </Popconfirm>
                : ''
              }
            </span>
          </Space>
        )}
        columns={columns}
        pagination={{
          defaultPageSize: 30,
          pageSizeOptions: ['15', '30', '60', '100', '500', '1000'],
          hideOnSinglePage: true,
        }}
        request={api.list}
      />
      <ReportForm
        visible={formReportVisible}
        ver={currentId}
        onCancel={() => {
          setFormReportVisible(false);
        }}
      />
      <ManualForm
        visible={formManualVisible}
        instIds={undefined}
        groupIds={undefined}
        serverIds={undefined}
        name={undefined}
        onCancel={() => {
          setFormManualVisible(false);
        }}
        onSubmit={() => {
          setFormManualVisible(false);
          actionRef?.current?.reload();
        }}
      />
    </PageContainer>
  );
};

export default OrderList;
